<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="运营审核"
    width="90%"
    draggable
    @close="close"
    :z-index="2000"
  >
    <div class="">
      <vxe-grid ref="tableRef" v-bind="tableOptions">
        <template #auditResult="{ row }">
          <el-select
            v-model="row.status"
            collapse-tags
            placeholder="请选择"
            clearable
            @change="changeStatus($event, row)"
            :disabled="Boolean(row.check_status)"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
        <template #auditRemark="{ row }">
          <el-input
            v-model="row.check_remark"
            placeholder="请输入"
            :rows="2"
            type="textarea"
            :disabled="Boolean(row.check_status)"
          />
        </template>
        <template #recommendedQuantity="{ row }">
          <el-input
            v-model="row.suggest_prepare_count"
            oninput="value=value.replace(/[^0-9]/g,'')"
            placeholder="请输入"
            :disabled="Boolean(row.check_status)"
          />
        </template>
      </vxe-grid>
    </div>
    <template #footer>
      <el-button @click="close">关闭</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave"> 保存 </el-button>
    </template>
  </el-dialog>
  <OperationAuditBatch
    ref="OperationAuditBatchRef"
    @submit="handleBatchConfirm"
  ></OperationAuditBatch>
</template>
<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import api from "../api";
import { statusOptions } from "../data.js";
import OperationAuditBatch from "./OperationAuditBatch.vue";
import {
  calculateSellingPriceRMB,
  calculateTotalCosts,
  calculateVATFee,
} from "../utils.js";
import { toNumber } from "@/utils/index.js";

const visible = ref(false);
const loading = ref(false);
const emit = defineEmits(["refresh"]);
const load = ref(false);
const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  tableOptions.data = data || [];
  visible.value = true;
};
const tableOptions = reactive({
  round: true,
  height: "600",
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  loading: false,
  data: [],
  columns: [
    {
      title: "审核结果",
      field: "review_opinion",
      width: "130",
      fixed: "left",
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              审核结果
              <div
                class="!text-[var(--el-color-primary)] cursor-pointer px-1"
                onClick={() => handleBatch("review_opinion")}
              >
                批量
              </div>
            </div>
          );
        },
        default: "auditResult",
      },
    },
    { title: "状态", field: "check_status_text", minWidth: "80", fixed: "left" },
    {
      title: "指定运营人员",
      field: "specified_operation_user_id",
      width: "170",
      fixed: "left",
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              指定运营人员
              <div
                class="!text-[var(--el-color-primary)] cursor-pointer px-1"
                onClick={() => handleBatch("specified_operation_user")}
              >
                批量
              </div>
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <select-personnel
                disabled={!(row.status == 3 && row.edit_special)}
                v-model={row.specified_operation_user_id}
                placeholder="请选择指定运营人员"
              ></select-personnel>
            </div>
          );
        },
      },
    },
    {
      title: "备货量",
      field: "recommended_quantity",
      width: "130",
      fixed: "left",
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              备货量
              <div
                class="!text-[var(--el-color-primary)] cursor-pointer px-1"
                onClick={() => handleBatch("recommended_quantity")}
              >
                批量
              </div>
            </div>
          );
        },
        default: "recommendedQuantity",
      },
    },
    {
      title: "审核备注",
      field: "review_remark",
      width: "200",
      fixed: "left",
      slots: {
        header: ({ row }) => {
          return (
            <div class="flex items-center">
              审核备注
              <div
                class="!text-[var(--el-color-primary)] cursor-pointer px-1"
                onClick={() => handleBatch("check_remark")}
              >
                批量
              </div>
            </div>
          );
        },
        default: "auditRemark",
      },
    },
    {
      title: "推荐平台/站点",
      field: "sku",
      width: "145",
      fixed: "left",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>
                <span>{row.product?.product_no || "-"}</span>
              </div>
              <span>{row.platform_id_text || "-"}</span>/
              <span>{row.site_text || "-"}</span>
            </div>
          );
        },
      },
    },
    { title: "建议销售价", field: "selling_price", minWidth: "100" },
    {
      title: "预估毛利率",
      field: "estimated_product_gross_margin",
      width: "160",
      slots: {
        header: () => {
          return (
            <div class="flex items-center">
              预估毛利率
              <el-tooltip
                placement="top"
                content="说明<br />1、预估产品毛利率={销售价*CNY汇率-（产品采购价+头程运费+尾程运费+平台佣金+其他费用+关税+VAT)}/（销售价*CNY汇率）<br />
                        2、预估销售毛利率=预估产品毛利率-广告费比率-退款率<br />3、平台佣金=建议销售价*佣金比例>"
                raw-content
              >
                <svg-icon class="ml-1" icon-class="QuestionFilled" />
              </el-tooltip>
            </div>
          );
        },
        default: ({ row }) => {
          return (
            <div>
              <div>产品毛利率:{calculateProductGross(row)}%</div>
              <div>销售毛利率:{calculateSaleGross(row)}%</div>
            </div>
          );
        },
      },
    },
    {
      title: "VAT税率",
      field: "vat_fee",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>费用:{calculateVATFee(row)}</div>
              <div>税率:{row.vat_tax}%</div>
            </div>
          );
        },
      },
    },
    {
      title: "备货金额",
      field: "stock_amount",
      width: "100",
      slots: {
        default: ({ row }) => {
          return <div> {calculateTotal(row)}</div>;
        },
      },
    },
    { title: "运营人员", field: "operation_user_id_text", width: "170" },
    { title: "汇率", field: "exchange_rate", width: "80" },
    { title: "采购成本", field: "purchase_cost", width: "80" },
    {
      title: "头程渠道",
      field: "head_logistic_channel",
      width: "160",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>渠道：{row.head_logistic_channel}</div>
              <div>运费：{row.head_freight}</div>
            </div>
          );
        },
      },
    },
    { title: "关税", field: "tariff", width: "80" },
    {
      title: "尾程渠道",
      field: "tail_logistic_channel",
      width: "160",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>渠道：{row.tail_logistic_channel}</div>
              <div>运费：{row.tail_freight}</div>
            </div>
          );
        },
      },
    },
    { title: "平台佣金", field: "platform_fee", width: "80" },
    { title: "广告费比率", field: "advertising_rate", width: "90" },
    { title: "退款率", field: "refund_rate", width: "80" },
    { title: "其它费用", field: "other_fee", width: "80" },
    {
      title: "竞品链接",
      field: "product_link",
      width: "200",
      slots: {
        default: ({ row }) => {
          return (
            <div title={row.product_link}>
              <el-link type="primary" href={row.product_link} target="_blank">
                {row.product_link}
              </el-link>
            </div>
          );
        },
      },
    },
    { title: "备注", field: "remark", width: "100" },
  ],
});

const handleAudit = (val) => {
  const data = tableOptions.data;
  const result = data.every((item) => item.review_opinion === val);
  if (result) {
    ElMessage.warning(val ? "已全部通过" : "已全部不通过");
    return;
  }
  data.forEach((item) => {
    item.review_opinion = val;
  });
  tableOptions.data = [...data];
};

const handleSave = () => {
  const data = tableOptions.data;

  // const isFalge = data?.some((item) => item.status);
  // if (!isFalge) return ElMessage.warning("请选择审核结果");
  const messageArray = [];
  data.map((item, index) => {
    if (!item.status && !item.check_status) {
      messageArray.push(`第${index + 1}项，审核结果不能为空`);
    }
    if (item.status === 3) {
      if (!item.specified_operation_user_id && !item.check_status) {
        messageArray.push(`第${index + 1}项，当审核结果为转运营时，指定运营人员不能为空`);
      }
      if (!item.check_remark) {
        messageArray.push(`第${index + 1}项，当审核结果为转运营时，审核备注必填`);
      }
    }
  });

  if (messageArray && messageArray.length) {
    ElMessageBox({
      title: "提示",
      message: () => <div>{messageArray.map((d) => h("p", null, d))}</div>,
    });
    return;
  }

  const params = data
    .filter((i) => i.check_status == 0)
    ?.map((item) => {
      return {
        id: item.id,
        check_status: item.status,
        check_remark: item.check_remark || null,
        specified_operation_user_id: item.specified_operation_user_id,
        suggest_prepare_count: item.suggest_prepare_count,
      };
    });
  loading.value = true;
  api
    .operationReview({ params: params })
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("审核成功!");
        close(true);
      } else {
        ElMessage.warning(res.message);
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleCancel = (row, flage) => {
  if (row.check_status === flage) {
    setTimeout(() => {
      row.check_status = undefined;
    }, 0);
  }
};

const OperationAuditBatchRef = ref();
const handleBatch = (type) => {
  OperationAuditBatchRef.value.open(type);
};

const close = (refresh) => {
  if (refresh) emit("refresh");
  visible.value = false;
};

const handleBatchConfirm = (row) => {
  if (row.type == "review_opinion") {
    tableOptions.data = tableOptions.data.map((i) => {
      if (!i.check_status) {
        i.status = row.status;
        i.specified_operation_user_id = "";
      }

      return i;
    });
  } else if (row.type == "specified_operation_user") {
    tableOptions.data = tableOptions.data.map((i) => {
      if (i.status == 3 && !i.check_status) {
        i.specified_operation_user_id = row.specified_operation_user_id;
      }
      return i;
    });
  } else if (row.type == "recommended_quantity") {
    tableOptions.data = tableOptions.data.map((i) => {
      if (!i.check_status) {
        i.suggest_prepare_count = row.suggest_prepare_count;
      }
      return i;
    });
  } else if (row.type == "check_remark") {
    tableOptions.data = tableOptions.data.map((i) => {
      if (!i.check_status) {
        i.check_remark = row.check_remark;
      }
      return i;
    });
  }
};

const changeStatus = (val, row) => {
  if (val != 3) {
    row.specified_operation_user_id = "";
  }
};

const calculateTotal = (row) => {
  const suggestPrepareCount = row.suggest_prepare_count || 0;
  const purchaseCost = row.purchase_cost || 0;

  // 根据业务逻辑判断是否允许负数
  if (Number(suggestPrepareCount) < 0 || Number(purchaseCost) < 0) {
    return 0; // 或者根据业务需求返回其他值
  }

  return Number(suggestPrepareCount) * Number(purchaseCost);
};

const calculateProductGross = (row) => {
  let marginRatio = 0;
  if (row.selling_price && row.exchange_rate) {
    try {
      const sellingPriceRMB = calculateSellingPriceRMB(
        toNumber(row.selling_price),
        toNumber(row.exchange_rate)
      );
      const totalCosts = calculateTotalCosts(
        row.purchase_cost,
        row.head_freight,
        row.tail_freight,
        row.platform_fee,
        row.other_fee,
        row.other_fee_currency,
        row.exchange_rate,
        sellingPriceRMB,
        row.vat_tax
      );
      const numerator =
        toNumber(row.selling_price) * toNumber(row.exchange_rate) - totalCosts;
      if (numerator <= 0) {
        throw new Error("Numerator must be greater than zero.");
      }

      marginRatio =
        numerator / (toNumber(row.selling_price) * toNumber(row.exchange_rate));
    } catch (error) {
      console.error("Failed to calculate estimated product gross margin:", error);
      return "0";
    }
  }
  const total = ((marginRatio || 0) * 100).toFixed(2);
  row.estimated_product_gross_margin = total;
  return total;
};

const calculateSaleGross = (row) => {
  let tate = 0;
  if (row.estimated_product_gross_margin > 0) {
    tate =
      toNumber(row.estimated_product_gross_margin) -
      toNumber(row?.advertising_rate) -
      toNumber(row?.refund_rate);
  }
  return tate.toFixed(2);
};

defineExpose({ open });
</script>
<style lang="scss" scoped>
.el-button--primary {
  :deep(span) {
    color: var(--el-color-primary) !important;
  }
}
</style>
